package com.moji.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.moji.common.config.AlipayConfig;
import com.moji.common.utils.HttpUtils;
import com.moji.entity.MjOrder;
import com.moji.entity.MjOrderDetail;
import com.moji.entity.dto.MojiRefuseDto;
import com.moji.entity.vo.MijiMoYaoVo1;
import com.moji.service.MjOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service

public class AlipayService {
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private MjOrderDetailService mjOrderDetailService;
    public Boolean refund(String orderCode,String total_amount) throws Exception {
        //获取要向支付宝支付的参数,由页面传过来
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderCode;
        //付款金额，必填,这里先定0.01
         total_amount = "0.01";
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.getAlipayGateWay(),
                alipayConfig.getAppId(), alipayConfig.getPrivateKey(),
                "json", "UTF-8", alipayConfig.getPublicKey(), "RSA2");
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest ();
//        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl()+order.getId());  //设置同步回调通知
        alipayRequest.setNotifyUrl(alipayConfig.getPayCallbackUrl());  //设置异步回调通知
        //设置支付参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("out_trade_no", out_trade_no);
        paramMap.put("refund_amount", total_amount);
        alipayRequest.setBizContent(JSON.toJSONString(paramMap));

        AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);
        // 5. 处理响应，通常需要检查`code`和`msg`字段
        if(response.isSuccess()){
            // 退款成功处理逻辑
            System.out.println("退款成功：" + response.getBody());
            //去除授权
            LambdaQueryWrapper<MjOrderDetail> mjOrderDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();
            mjOrderDetailLambdaQueryWrapper.eq(MjOrderDetail::getOrderCode,orderCode);
            List<MjOrderDetail> list = mjOrderDetailService.list(mjOrderDetailLambdaQueryWrapper);
            if (list != null&&list.size()>0) {
                for (int i = 0; i < list.size(); i++) {
                MojiRefuseDto mojiRefuseDto=new MojiRefuseDto();
                if(list.get(i).getSpareInt2()!=null)
                {
                    mojiRefuseDto.setAccessId(list.get(i).getSpareInt2());
                    Gson gson = new Gson();
                    // 将对象转换为JSON字符串
                    String jsonString = gson.toJson(mojiRefuseDto);
                    String s = HttpUtils.sendPutRequest("/tob-data-misc/eshop/access/deactivation", jsonString);
                    Gson gson1 = new Gson();
                    MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
                    if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
                        //去消授权成功
                        MjOrderDetail mjOrderDetail = list.get(i);
                        mjOrderDetail.setSpareString2(null);
                        mjOrderDetail.setSpareInt2(null);
                        mjOrderDetailService.updateById(mjOrderDetail);
                    }
                }

                }
            }
            return true;
        } else {
            // 退款失败处理逻辑
            System.out.println("退款失败：" + response.getSubCode() + " - " + response.getSubMsg());
        }
        return false;
    }

    /**
     * 微信统一下单方法 生成用户扫码支付的二维码的URL
     * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
     * 除付款码支付场景以外，商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易会话标识后再按Native、JSAPI、APP等不同场景生成交易串调起支付。
     *
     * @return
     */

    private String getParamStr(Map<String, String> map) {
        ArrayList list = new ArrayList();
        for (Map.Entry entry : map.entrySet()) {
            if (entry.getValue() != "") {
                list.add(new StringBuilder().append((String) entry.getKey()).append("=").append((String) entry.getValue()).append("&").toString());
            }
        }
        int size = list.size();
        String[] arrayToSort = (String[]) list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = "";
        if (sb.length() > 0)
            result = sb.subSequence(0, sb.length() - 1).toString();
        else {
            result = sb.toString();
        }
        return result;
    }

//    public static void main(String[] args) throws AlipayApiException {
//        // 配置参数
//
//        String out_trade_no = "DD-240918-0007";
//        //付款金额，必填
//        String total_amount = "0.01";
//        //获得初始化的AlipayClient
//        String alipayGateWay = AlipayConfig.getAlipayGateWay();
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.getAlipayGateWay(),
//                "2021004144614528", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAyDREmk7/M2in55QdPNq9ScayBuw2xdVPqVvM9a7BLqB4/3MBa4OX84A8JareUaV4yFUg5pOIY4vFmXOCHvYe51HDr/GplTnF3raFIez6bkktkL6NwqBMrnHvzw96d/u+CyjROibCnwzyI9xIs5jXrFB7enC4XDJB7gTJJy7SgidsT90QqWSTz2WGmsgoFRIWeM8JBI8D9NoNAIQsMXV0MM1MLV4Q8JaHOMEYpUyFE7MXPIsEmPz6IH7FPCLOvg8YYH9CTNwsQahb0LbRZpXaxodhUo6apMZ+LbyVi4Qk+DsHe+S220BsPu9tmN/gJAbmmSsLzkw9mH2b9227s8D9AgMBAAECggEAAoXpoD51tcJIFqIO4NPEZVkAr5Q7JIeTuk/TIJzfo6FKO5SlqC13Eo8OwB7szhZDa65hHJfn5BAvONvcy3vXzpsxmufjkDMAQsQuR0V24yEuBdqEITri8R2p1cz0vK2FHSAS2KaPA9kh48yYEESUhgU2PnUTqEkGIwyKw3YlELK8nyGobuvQAJMiHkv6L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CgKCAQEAsHAWqMNfoekxS7UmQbN06Df3B0jhXENeq56Z7W/sxYR+WexLokBGFW4eBsffs8BSPrRDL8wRcWkn2OJX9rg5VJggF7wTa5ACrJY96+iRq2JCYQ5CvCZdFffdjfURR50bcJZtCBNFAYdG1A3YCcsIHffeyA3Qv+YKPeBkGtujIz9f+G2D7+vyBcAuL5fAr0CsqSn2QIo7MBIhpsUhq5ajjWo5GiA/Aa++5XZvIyhV3noG/nKSS01m2Td3qLGeoJCL5i9Tj6oPfDeg4nHWrNf6fCrak213/xndl0XR9BCfaxqccI6HcZLCYT5Sf+yYb1yWNd012QQiiyVbOmbZU1FzxQIDAQAB", "RSA2");
//        //设置请求参数
//        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest ();
////        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl()+order.getId());  //设置同步回调通知
//        alipayRequest.setNotifyUrl("http://47.93.153.16:8082/web/alipay/callback");  //设置异步回调通知
//        //设置支付参数
//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("out_trade_no", out_trade_no);
//        paramMap.put("refund_amount", total_amount);
////        paramMap.put("subject", subject);
////        paramMap.put("body", body);
////        paramMap.put("product_code", "FAST_INSTANT_TRADE_PAY");
//        alipayRequest.setBizContent(JSON.toJSONString(paramMap));
//
//        AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);
//        // 5. 处理响应，通常需要检查`code`和`msg`字段
//        if(response.isSuccess()){
//            // 退款成功处理逻辑
//            System.out.println("退款成功：" + response.getBody());
//        } else {
//            // 退款失败处理逻辑
//            System.out.println("退款失败：" + response.getSubCode() + " - " + response.getSubMsg());
//        }
//
//    }
}
